package com.agileboot.domain.performance.score;

import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.performance.score.command.AddUserScoreRecordCommand;
import com.agileboot.domain.performance.score.command.UpdateUserScoreRecordCommand;
import com.agileboot.domain.performance.score.db.UserScoreRecordEntity;
import com.agileboot.domain.performance.score.db.UserScoreRecordService;
import com.agileboot.domain.performance.score.dto.UserScoreRecordDTO;
import com.agileboot.domain.performance.score.dto.UserScoreRecordImportResultDTO;
import com.agileboot.domain.performance.score.dto.UserScoreRecordImportTemplateDTO;
import com.agileboot.domain.performance.score.model.UserScoreRecordModel;
import com.agileboot.domain.performance.score.model.UserScoreRecordModelFactory;
import com.agileboot.domain.performance.score.query.UserScoreRecordQuery;
import com.agileboot.domain.performance.submission.db.SubmissionEntity;
import com.agileboot.domain.performance.submission.db.SubmissionService;
import com.agileboot.domain.performance.teaching.db.TeachingWorkloadEntity;
import com.agileboot.domain.performance.teaching.db.TeachingWorkloadService;
import com.agileboot.domain.system.dept.db.SysDeptEntity;
import com.agileboot.domain.system.dept.db.SysDeptService;
import com.agileboot.domain.system.user.db.SysUserEntity;
import com.agileboot.domain.system.user.db.SysUserService;
import com.agileboot.domain.performance.score.dto.RateLimitInfoDTO;
import com.agileboot.infrastructure.cache.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户分数记录应用服务类
 */
@Service
@RequiredArgsConstructor
public class UserScoreRecordApplicationService {

    private final UserScoreRecordModelFactory userScoreRecordModelFactory;
    private final UserScoreRecordService userScoreRecordService;
    private final SysUserService sysUserService;
    private final SysDeptService sysDeptService;
    private final SubmissionService submissionService;
    private final TeachingWorkloadService teachingWorkloadService;
    private final UserScoreCalculationQueue calculationQueue;
    private final RedisUtil redisUtil;

    /**
     * 批量统计接口的Redis缓存键
     */
    private static final String CACHE_KEY_BATCH_CALCULATE_LAST_TIME = "performance:batch_calculate:last_time";
    
    /**
     * 限流时间间隔（分钟）
     */
    private static final int RATE_LIMIT_INTERVAL_MINUTES = 10;

    public PageDTO<UserScoreRecordDTO> getUserScoreRecordList(UserScoreRecordQuery query) {
        Page<UserScoreRecordEntity> page = userScoreRecordService.page(query.toPage(), query.toQueryWrapper());
        List<UserScoreRecordDTO> records = convertEntitiesToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    public UserScoreRecordDTO getUserScoreRecordInfo(Long id) {
        UserScoreRecordEntity entity = userScoreRecordService.getById(id);
        if (entity == null) {
            return null;
        }
        return convertEntitiesToDTOs(List.of(entity)).get(0);
    }

    public void addUserScoreRecord(AddUserScoreRecordCommand addCommand) {
        UserScoreRecordModel model = userScoreRecordModelFactory.create();
        model.loadFromAddCommand(addCommand);
        model.insert();
    }

    public void updateUserScoreRecord(UpdateUserScoreRecordCommand updateCommand) {
        UserScoreRecordModel model = userScoreRecordModelFactory.loadById(updateCommand.getId());
        model.loadFromUpdateCommand(updateCommand);
        model.updateById();
    }

    public void deleteUserScoreRecord(List<Long> ids) {
        userScoreRecordService.removeBatchByIds(ids);
    }

    /**
     * 获取所有用户分数记录列表
     */
    public List<UserScoreRecordDTO> getUserScoreRecordListAll(UserScoreRecordQuery query) {
        List<UserScoreRecordEntity> all = userScoreRecordService.list(query.toQueryWrapper());
        return convertEntitiesToDTOs(all);
    }

    /**
     * 将实体列表转换为DTO列表，并填充用户名称和部门名称信息
     * @param entities UserScoreRecordEntity列表
     * @return UserScoreRecordDTO列表
     */
    private List<UserScoreRecordDTO> convertEntitiesToDTOs(List<UserScoreRecordEntity> entities) {
        if (entities.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集所有需要查询的用户ID
        Set<Long> userIds = entities.stream()
                .filter(entity -> entity != null && entity.getUserId() != null)
                .map(UserScoreRecordEntity::getUserId)
                .collect(Collectors.toSet());

        // 批量获取用户信息
        Map<Long, SysUserEntity> userMap;
        if (!userIds.isEmpty()) {
            List<SysUserEntity> userEntities = sysUserService.getByUserIds(new ArrayList<>(userIds));
            userMap = userEntities.stream()
                    .filter(user -> user != null)
                    .collect(Collectors.toMap(
                            SysUserEntity::getUserId,
                            user -> user,
                            (existing, replacement) -> existing
                    ));
        } else {
            userMap = Collections.emptyMap();
        }

        // 从用户信息中收集部门ID
        Set<Long> deptIds = userMap.values().stream()
                .filter(user -> user.getDeptId() != null)
                .map(SysUserEntity::getDeptId)
                .collect(Collectors.toSet());

        // 批量获取部门信息
        Map<Long, SysDeptEntity> deptMap;
        if (!deptIds.isEmpty()) {
            List<SysDeptEntity> deptEntities = sysDeptService.getByDeptIds(new ArrayList<>(deptIds));
            deptMap = deptEntities.stream()
                    .filter(dept -> dept != null)
                    .collect(Collectors.toMap(
                            SysDeptEntity::getDeptId,
                            dept -> dept,
                            (existing, replacement) -> existing
                    ));
        } else {
            deptMap = Collections.emptyMap();
        }

        // 转换为DTO并填充用户名称和部门名称
        final Map<Long, SysUserEntity> finalUserMap = userMap;
        final Map<Long, SysDeptEntity> finalDeptMap = deptMap;
        return entities.stream().map(entity -> {
            UserScoreRecordDTO dto = new UserScoreRecordDTO(entity);

            // 设置用户姓名和部门名称
            if (entity.getUserId() != null) {
                SysUserEntity user = finalUserMap.get(entity.getUserId());
                if (user != null) {
                    dto.setUserName(user.getNickname());
                    
                    // 根据用户的部门ID设置部门名称
                    if (user.getDeptId() != null) {
                        SysDeptEntity dept = finalDeptMap.get(user.getDeptId());
                        if (dept != null) {
                            dto.setDeptName(dept.getDeptName());
                        }
                    }
                }
            }

            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 获取导入模板数据
     * 返回所有未删除用户的信息
     * @return 导入模板数据列表
     */
    public List<UserScoreRecordImportTemplateDTO> getImportTemplate() {
        // 查询所有未删除的用户
        QueryWrapper<SysUserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("deleted", 0);
        List<SysUserEntity> users = sysUserService.list(userQueryWrapper);

        if (users.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集部门ID
        Set<Long> deptIds = users.stream()
                .filter(user -> user.getDeptId() != null)
                .map(SysUserEntity::getDeptId)
                .collect(Collectors.toSet());

        // 批量获取部门信息
        Map<Long, SysDeptEntity> deptMap;
        if (!deptIds.isEmpty()) {
            List<SysDeptEntity> deptEntities = sysDeptService.getByDeptIds(new ArrayList<>(deptIds));
            deptMap = deptEntities.stream()
                    .filter(dept -> dept != null)
                    .collect(Collectors.toMap(
                            SysDeptEntity::getDeptId,
                            dept -> dept,
                            (existing, replacement) -> existing
                    ));
        } else {
            deptMap = Collections.emptyMap();
        }

        // 转换为模板DTO
        final Map<Long, SysDeptEntity> finalDeptMap = deptMap;
        return users.stream().map(user -> {
            UserScoreRecordImportTemplateDTO template = new UserScoreRecordImportTemplateDTO();
            template.setUserId(user.getUserId());
            template.setNickname(user.getNickname());

            // 设置部门名称
            if (user.getDeptId() != null) {
                SysDeptEntity dept = finalDeptMap.get(user.getDeptId());
                if (dept != null) {
                    template.setDeptName(dept.getDeptName());
                }
            }

            return template;
        }).collect(Collectors.toList());
    }

    /**
     * 批量导入用户分数记录
     * 如果该用户的数据已存在（userId），则覆盖，否则新增
     * @param importDataList 导入数据列表
     * @return 导入结果
     */
    @Transactional(rollbackFor = Exception.class)
    public UserScoreRecordImportResultDTO batchImport(List<UserScoreRecordImportTemplateDTO> importDataList) {
        UserScoreRecordImportResultDTO result = new UserScoreRecordImportResultDTO();
        List<UserScoreRecordImportResultDTO.ImportFailureDetail> failureDetails = new ArrayList<>();
        int successCount = 0;
        int failCount = 0;

        if (importDataList == null || importDataList.isEmpty()) {
            result.setSuccessCount(0);
            result.setFailCount(0);
            result.setFailureDetails(Collections.emptyList());
            return result;
        }

        // 1. 批量查询所有现有数据，构建 userId -> Entity 的映射
        List<UserScoreRecordEntity> allExistingRecords = userScoreRecordService.list();
        Map<Long, UserScoreRecordEntity> existingDataMap = allExistingRecords.stream()
                .filter(entity -> entity.getUserId() != null)
                .collect(Collectors.toMap(
                        UserScoreRecordEntity::getUserId,
                        entity -> entity,
                        (existing, replacement) -> existing
                ));

        // 2. 收集所有需要查询的用户ID，批量获取用户信息
        Set<Long> userIds = importDataList.stream()
                .filter(data -> data != null && data.getUserId() != null)
                .map(UserScoreRecordImportTemplateDTO::getUserId)
                .collect(Collectors.toSet());

        Map<Long, SysUserEntity> userMap;
        if (!userIds.isEmpty()) {
            List<SysUserEntity> userEntities = sysUserService.getByUserIds(new ArrayList<>(userIds));
            userMap = userEntities.stream()
                    .filter(user -> user != null)
                    .collect(Collectors.toMap(
                            SysUserEntity::getUserId,
                            user -> user,
                            (existing, replacement) -> existing
                    ));
        } else {
            userMap = Collections.emptyMap();
        }

        // 3. 分类处理：收集需要新增和更新的数据
        List<UserScoreRecordEntity> entitiesToInsert = new ArrayList<>();
        List<UserScoreRecordEntity> entitiesToUpdate = new ArrayList<>();

        for (int i = 0; i < importDataList.size(); i++) {
            UserScoreRecordImportTemplateDTO importData = importDataList.get(i);
            int rowNumber = i + 2; // Excel行号从2开始（第1行是标题）

            try {
                // 验证数据
                String validationError = validateImportData(importData);
                if (validationError != null) {
                    failCount++;
                    failureDetails.add(createFailureDetail(rowNumber, importData, validationError));
                    continue;
                }

                // 验证用户是否存在
                SysUserEntity user = userMap.get(importData.getUserId());
                if (user == null) {
                    failCount++;
                    failureDetails.add(createFailureDetail(rowNumber, importData, "用户ID不存在或用户已被删除"));
                    continue;
                }

                // 判断是新增还是更新
                UserScoreRecordEntity existingEntity = existingDataMap.get(importData.getUserId());
                if (existingEntity != null) {
                    // 更新现有数据
                    existingEntity.setResearchWorkload(importData.getResearchWorkload() != null ? importData.getResearchWorkload() : BigDecimal.ZERO);
                    existingEntity.setTeachingWorkload(importData.getTeachingWorkload() != null ? importData.getTeachingWorkload() : BigDecimal.ZERO);
                    existingEntity.setEducationWorkload(importData.getEducationWorkload() != null ? importData.getEducationWorkload() : BigDecimal.ZERO);
                    existingEntity.setServiceWorkload(importData.getServiceWorkload() != null ? importData.getServiceWorkload() : BigDecimal.ZERO);
                    existingEntity.setOtherWorkload(importData.getOtherWorkload() != null ? importData.getOtherWorkload() : BigDecimal.ZERO);
                    existingEntity.setGeneralCourseScore(importData.getGeneralCourseScore() != null ? importData.getGeneralCourseScore() : BigDecimal.ZERO);
                    existingEntity.setMajorCourseScore(importData.getMajorCourseScore() != null ? importData.getMajorCourseScore() : BigDecimal.ZERO);
                    existingEntity.setLabCourseScore(importData.getLabCourseScore() != null ? importData.getLabCourseScore() : BigDecimal.ZERO);
                    existingEntity.setPendingScore(importData.getPendingScore() != null ? importData.getPendingScore() : BigDecimal.ZERO);
                    existingEntity.setApprovedTotalScore(importData.getApprovedTotalScore() != null ? importData.getApprovedTotalScore() : BigDecimal.ZERO);
                    entitiesToUpdate.add(existingEntity);
                } else {
                    // 新增数据
                    UserScoreRecordEntity newEntity = new UserScoreRecordEntity();
                    newEntity.setUserId(importData.getUserId());
                    newEntity.setResearchWorkload(importData.getResearchWorkload() != null ? importData.getResearchWorkload() : BigDecimal.ZERO);
                    newEntity.setTeachingWorkload(importData.getTeachingWorkload() != null ? importData.getTeachingWorkload() : BigDecimal.ZERO);
                    newEntity.setEducationWorkload(importData.getEducationWorkload() != null ? importData.getEducationWorkload() : BigDecimal.ZERO);
                    newEntity.setServiceWorkload(importData.getServiceWorkload() != null ? importData.getServiceWorkload() : BigDecimal.ZERO);
                    newEntity.setOtherWorkload(importData.getOtherWorkload() != null ? importData.getOtherWorkload() : BigDecimal.ZERO);
                    newEntity.setGeneralCourseScore(importData.getGeneralCourseScore() != null ? importData.getGeneralCourseScore() : BigDecimal.ZERO);
                    newEntity.setMajorCourseScore(importData.getMajorCourseScore() != null ? importData.getMajorCourseScore() : BigDecimal.ZERO);
                    newEntity.setLabCourseScore(importData.getLabCourseScore() != null ? importData.getLabCourseScore() : BigDecimal.ZERO);
                    newEntity.setPendingScore(importData.getPendingScore() != null ? importData.getPendingScore() : BigDecimal.ZERO);
                    newEntity.setApprovedTotalScore(importData.getApprovedTotalScore() != null ? importData.getApprovedTotalScore() : BigDecimal.ZERO);
                    entitiesToInsert.add(newEntity);
                }

                successCount++;

            } catch (Exception e) {
                failCount++;
                failureDetails.add(createFailureDetail(rowNumber, importData, "导入失败: " + e.getMessage()));
            }
        }

        // 4. 批量插入和批量更新
        if (!entitiesToInsert.isEmpty()) {
            userScoreRecordService.saveBatch(entitiesToInsert);
        }
        if (!entitiesToUpdate.isEmpty()) {
            userScoreRecordService.updateBatchById(entitiesToUpdate);
        }

        result.setSuccessCount(successCount);
        result.setFailCount(failCount);
        result.setFailureDetails(failureDetails);

        return result;
    }

    /**
     * 验证导入数据
     * @param importData 导入数据
     * @return 验证错误信息，如果验证通过返回null
     */
    private String validateImportData(UserScoreRecordImportTemplateDTO importData) {
        if (importData.getUserId() == null) {
            return "用户ID不能为空";
        }

        // 验证分数不能为负数
        if (importData.getResearchWorkload() != null && importData.getResearchWorkload().compareTo(BigDecimal.ZERO) < 0) {
            return "科研工作量不能为负数";
        }

        if (importData.getTeachingWorkload() != null && importData.getTeachingWorkload().compareTo(BigDecimal.ZERO) < 0) {
            return "教研工作量不能为负数";
        }

        if (importData.getEducationWorkload() != null && importData.getEducationWorkload().compareTo(BigDecimal.ZERO) < 0) {
            return "育人工作量不能为负数";
        }

        if (importData.getServiceWorkload() != null && importData.getServiceWorkload().compareTo(BigDecimal.ZERO) < 0) {
            return "服务工作量不能为负数";
        }

        if (importData.getOtherWorkload() != null && importData.getOtherWorkload().compareTo(BigDecimal.ZERO) < 0) {
            return "其他工作量不能为负数";
        }

        if (importData.getGeneralCourseScore() != null && importData.getGeneralCourseScore().compareTo(BigDecimal.ZERO) < 0) {
            return "通用课程分数不能为负数";
        }

        if (importData.getMajorCourseScore() != null && importData.getMajorCourseScore().compareTo(BigDecimal.ZERO) < 0) {
            return "专业课程分数不能为负数";
        }

        if (importData.getLabCourseScore() != null && importData.getLabCourseScore().compareTo(BigDecimal.ZERO) < 0) {
            return "实验课程分数不能为负数";
        }

        if (importData.getPendingScore() != null && importData.getPendingScore().compareTo(BigDecimal.ZERO) < 0) {
            return "待审核分数不能为负数";
        }

        if (importData.getApprovedTotalScore() != null && importData.getApprovedTotalScore().compareTo(BigDecimal.ZERO) < 0) {
            return "已审核总分不能为负数";
        }

        return null;
    }

    /**
     * 创建失败详情
     */
    private UserScoreRecordImportResultDTO.ImportFailureDetail createFailureDetail(
            int rowNumber, UserScoreRecordImportTemplateDTO importData, String failureReason) {
        UserScoreRecordImportResultDTO.ImportFailureDetail detail = 
                new UserScoreRecordImportResultDTO.ImportFailureDetail();
        detail.setRowNumber(rowNumber);
        detail.setUserId(importData.getUserId());
        detail.setNickname(importData.getNickname());
        detail.setFailureReason(failureReason);
        detail.setData(importData);
        return detail;
    }

    /**
     * 异步提交用户分数统计任务
     * @param userId 用户ID
     */
    public void submitCalculateUserScoreTask(Long userId) {
        if (userId == null) {
            return;
        }
        calculationQueue.submitTask(userId);
    }

    /**
     * 检查批量统计接口的限流
     * @return 如果未到限流时间返回null，否则返回限流信息
     */
    public RateLimitInfoDTO checkBatchCalculateRateLimit() {
        // 获取上次调用时间
        Long lastTimeMillis = redisUtil.getCacheObject(CACHE_KEY_BATCH_CALCULATE_LAST_TIME);
        
        if (lastTimeMillis == null) {
            // 第一次调用，允许执行
            return null;
        }
        
        long currentTimeMillis = System.currentTimeMillis();
        long elapsedMillis = currentTimeMillis - lastTimeMillis;
        long limitIntervalMillis = RATE_LIMIT_INTERVAL_MINUTES * 60 * 1000L;
        
        if (elapsedMillis < limitIntervalMillis) {
            // 未到时间，计算下次可调用时间
            long remainingMillis = limitIntervalMillis - elapsedMillis;
            long remainingSeconds = remainingMillis / 1000;
            // 使用毫秒数精确计算下次可调用时间
            long nextAvailableTimeMillis = lastTimeMillis + limitIntervalMillis;
            LocalDateTime nextAvailableTime = LocalDateTime.ofInstant(
                java.time.Instant.ofEpochMilli(nextAvailableTimeMillis),
                java.time.ZoneId.systemDefault()
            );
            
            RateLimitInfoDTO rateLimitInfo = new RateLimitInfoDTO();
            rateLimitInfo.setNextAvailableTime(nextAvailableTime);
            rateLimitInfo.setRemainingSeconds(remainingSeconds);
            
            return rateLimitInfo;
        }
        
        // 已到时间，允许执行
        return null;
    }

    /**
     * 批量提交所有用户的分数统计任务
     * 获取所有未删除的用户，为每个用户提交统计任务
     */
    public void submitCalculateAllUsersScoreTask() {
        // 更新调用时间到Redis，设置过期时间为11分钟（略大于限流间隔）
        long currentTimeMillis = System.currentTimeMillis();
        redisUtil.setCacheObject(CACHE_KEY_BATCH_CALCULATE_LAST_TIME, currentTimeMillis, 
            RATE_LIMIT_INTERVAL_MINUTES + 1, TimeUnit.MINUTES);
        
        // 查询所有未删除的用户
        QueryWrapper<SysUserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("deleted", 0);
        List<SysUserEntity> users = sysUserService.list(userQueryWrapper);

        // 为每个用户提交统计任务
        for (SysUserEntity user : users) {
            if (user.getUserId() != null) {
                calculationQueue.submitTask(user.getUserId());
            }
        }
    }

    /**
     * 统计用户分数
     * 根据用户ID统计该用户的所有分数并更新或创建用户分数记录
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void calculateUserScore(Long userId) {
        if (userId == null) {
            return;
        }

        // 1. 查询用户信息，获取deptId
        SysUserEntity user = sysUserService.getById(userId);
        if (user == null) {
            return;
        }
        Long deptId = user.getDeptId();
        int currentYear = LocalDate.now().getYear();

        // 2. 统计四个工作量字段：从submissions表查询，owner=userId, status='APPROVED'，根据main_category分类统计
        QueryWrapper<SubmissionEntity> approvedQuery = new QueryWrapper<>();
        approvedQuery.eq("owner", userId)
                .eq("status", "APPROVED");
        List<SubmissionEntity> approvedSubmissions = submissionService.list(approvedQuery);

        BigDecimal researchWorkload = BigDecimal.ZERO;
        BigDecimal teachingWorkloadTotal = BigDecimal.ZERO;
        BigDecimal educationWorkload = BigDecimal.ZERO;
        BigDecimal serviceWorkload = BigDecimal.ZERO;
        BigDecimal otherWorkload = BigDecimal.ZERO;

        for (SubmissionEntity submission : approvedSubmissions) {
            if (submission.getOwnerScore() == null) {
                continue;
            }
            BigDecimal score = BigDecimal.valueOf(submission.getOwnerScore());
            String mainCategory = submission.getMainCategory();
            
            if ("科研工作量".equals(mainCategory)) {
                researchWorkload = researchWorkload.add(score);
            } else if ("教研工作量".equals(mainCategory)) {
                teachingWorkloadTotal = teachingWorkloadTotal.add(score);
            } else if ("育人工作量".equals(mainCategory)) {
                educationWorkload = educationWorkload.add(score);
            } else if ("服务工作量".equals(mainCategory)) {
                serviceWorkload = serviceWorkload.add(score);
            } else if ("其他工作量".equals(mainCategory)) {
                otherWorkload = otherWorkload.add(score);
            }
        }

        // 3. 统计三个课程分数字段：从teaching_workloads表查询，userId匹配
        QueryWrapper<TeachingWorkloadEntity> teachingQuery = new QueryWrapper<>();
        teachingQuery.eq("user_id", userId);
        List<TeachingWorkloadEntity> teachingWorkloads = teachingWorkloadService.list(teachingQuery);
        
        BigDecimal generalCourseScore = BigDecimal.ZERO;
        BigDecimal majorCourseScore = BigDecimal.ZERO;
        BigDecimal labCourseScore = BigDecimal.ZERO;

        for (TeachingWorkloadEntity teachingWorkload : teachingWorkloads) {
            if (teachingWorkload.getGeneralCourseScore() != null) {
                generalCourseScore = generalCourseScore.add(BigDecimal.valueOf(teachingWorkload.getGeneralCourseScore()));
            }
            if (teachingWorkload.getSubjectCourseScore() != null) {
                majorCourseScore = majorCourseScore.add(BigDecimal.valueOf(teachingWorkload.getSubjectCourseScore()));
            }
            if (teachingWorkload.getLabCourseScore() != null) {
                labCourseScore = labCourseScore.add(BigDecimal.valueOf(teachingWorkload.getLabCourseScore()));
            }
        }

        // 4. 统计pendingScore：从submissions表查询，owner=userId, status='PENDING_AUDIT'，统计owner_score总和
        QueryWrapper<SubmissionEntity> pendingQuery = new QueryWrapper<>();
        pendingQuery.eq("owner", userId)
                .eq("status", "PENDING_AUDIT");
        List<SubmissionEntity> pendingSubmissions = submissionService.list(pendingQuery);
        
        BigDecimal pendingScore = BigDecimal.ZERO;
        for (SubmissionEntity submission : pendingSubmissions) {
            if (submission.getOwnerScore() != null) {
                pendingScore = pendingScore.add(BigDecimal.valueOf(submission.getOwnerScore()));
            }
        }

        // 5. 计算approvedTotalScore：前面所有分数的总和
        BigDecimal approvedTotalScore = researchWorkload
                .add(teachingWorkloadTotal)
                .add(educationWorkload)
                .add(serviceWorkload)
                .add(otherWorkload)
                .add(generalCourseScore)
                .add(majorCourseScore)
                .add(labCourseScore);

        // 6. 查询或创建用户分数记录
        QueryWrapper<UserScoreRecordEntity> recordQuery = new QueryWrapper<>();
        recordQuery.eq("user_id", userId);
        UserScoreRecordEntity existingRecord = userScoreRecordService.getOne(recordQuery);

        if (existingRecord != null) {
            // 更新现有记录
            existingRecord.setDeptId(deptId);
            existingRecord.setAssessmentYear(currentYear);
            existingRecord.setResearchWorkload(researchWorkload);
            existingRecord.setTeachingWorkload(teachingWorkloadTotal);
            existingRecord.setEducationWorkload(educationWorkload);
            existingRecord.setServiceWorkload(serviceWorkload);
            existingRecord.setOtherWorkload(otherWorkload);
            existingRecord.setGeneralCourseScore(generalCourseScore);
            existingRecord.setMajorCourseScore(majorCourseScore);
            existingRecord.setLabCourseScore(labCourseScore);
            existingRecord.setPendingScore(pendingScore);
            existingRecord.setApprovedTotalScore(approvedTotalScore);
            userScoreRecordService.updateById(existingRecord);
        } else {
            // 创建新记录
            UserScoreRecordEntity newRecord = new UserScoreRecordEntity();
            newRecord.setUserId(userId);
            newRecord.setAssessmentYear(currentYear);
            newRecord.setCreatorId(userId);
            newRecord.setUpdaterId(userId);
            newRecord.setCreateTime(new Date());
            newRecord.setUpdateTime(new Date());
            newRecord.setDeleted(false);  
            newRecord.setDeptId(deptId);
            newRecord.setResearchWorkload(researchWorkload);
            newRecord.setTeachingWorkload(teachingWorkloadTotal);
            newRecord.setEducationWorkload(educationWorkload);
            newRecord.setServiceWorkload(serviceWorkload);
            newRecord.setOtherWorkload(otherWorkload);
            newRecord.setGeneralCourseScore(generalCourseScore);
            newRecord.setMajorCourseScore(majorCourseScore);
            newRecord.setLabCourseScore(labCourseScore);
            newRecord.setPendingScore(pendingScore);
            newRecord.setApprovedTotalScore(approvedTotalScore);
            userScoreRecordService.save(newRecord);
        }
        
        // 清除用户统计缓存
        clearUserStatisticsCache(userId);
    }
    
    /**
     * 清除用户统计缓存
     * @param userId 用户ID
     */
    private void clearUserStatisticsCache(Long userId) {
        if (userId != null) {
            String cacheKey = "performance:user_statistics:" + userId;
            redisUtil.deleteObject(cacheKey);
        }
    }
}

